package com.fubowen.lepton.helper

import android.graphics.Bitmap
import android.os.Bundle
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.fubowen.lepton.helper.ViewHelper.createBitmapFromView

object FragmentHelper {

    fun Fragment.clone(): Fragment {
        return try {
            val savedState = parentFragmentManager.saveFragmentInstanceState(this)
            val newInstance = this.javaClass.newInstance()
            newInstance.setInitialSavedState(savedState)
            newInstance
        } catch (e: Exception) {
            throw RuntimeException("不能重新创建新实例 " + this.javaClass.name, e)
        }
    }

    fun FragmentManager.getOrCreateFragment(
        savedInstanceState: Bundle?,
        tag: String?,
        tClass: Class<*>
    ): Fragment {
        if (tag.isNullOrEmpty() && savedInstanceState != null) {
            return this.findFragmentByTag(tag) ?: tClass.newInstance() as Fragment
        }
        return tClass.newInstance() as Fragment
    }


    fun FragmentManager.currentFragment(): Fragment? {
        val stackSize = this.backStackEntryCount
        if (stackSize > 0) {
            val backStackEntry = this.getBackStackEntryAt(stackSize - 1)
            val tag = backStackEntry.name
            return this.findFragmentByTag(tag)
        }
        return null
    }

    fun FragmentManager.currentFragmentBitmap(callback: (Bitmap?) -> Unit) {
        val stackSize = this.backStackEntryCount
        if (stackSize > 0) {
            val backStackEntry = this.getBackStackEntryAt(stackSize - 1)
            val tag = backStackEntry.name
            val fragment = this.findFragmentByTag(tag)
            val window = fragment?.activity?.window
            if (window != null) {
                fragment.view?.createBitmapFromView(window) { bitmap, _ ->
                    callback(bitmap)
                }
            }
        }
        callback(null)
    }

    fun Fragment.hideSystemUI() {
        val controller = WindowCompat.getInsetsController(
            requireActivity().window,
            requireActivity().window.decorView
        )
        controller.hide(WindowInsetsCompat.Type.systemBars())
    }

    fun Fragment.showSystemUI() {
        val controller = WindowCompat.getInsetsController(
            requireActivity().window,
            requireActivity().window.decorView
        )
        controller.show(WindowInsetsCompat.Type.systemBars())
    }
}